import request from '@/utils/http'

// 角色响应（与后端 RoleResponse 对齐）
export interface RoleResponse {
  id?: number
  name: string
  desc?: string | null
  status?: boolean
  create_time?: string
  update_time?: string
}

// 列表响应
export interface RoleListResponse {
  total: number
  items: RoleResponse[]
  page: number
  size: number
  pages: number
}

// 创建/更新请求体
export interface RoleCreate {
  name: string
  desc?: string | null
  status?: boolean
}

export interface RoleUpdate {
  name?: string
  desc?: string | null
  status?: boolean
}

// 查询参数（与后端 RoleQuery 对齐），注意 current 是 page 的别名
export interface RoleQuery {
  current?: number
  size?: number
  name?: string
  status?: boolean
  keyword?: string
}

// 权限响应与更新请求
export interface RolePermissionsResponse {
  role_id: number
  permission_ids: number[]
}

export interface RolePermissionsUpdateRequest {
  permission_ids: number[]
}

/**
 * 创建角色
 */
export function createRole(params: RoleCreate) {
  return request.post<RoleResponse>({
    url: '/system/roles/create',
    params,
    showSuccessMessage: true
  })
}

/**
 * 获取角色列表（分页）
 */
export function fetchRoleList(params: RoleQuery) {
  return request.post<RoleListResponse>({
    url: '/system/roles/list',
    params
  })
}

/**
 * 更新角色
 */
export function updateRole(roleId: number, params: RoleUpdate) {
  return request.put<RoleResponse>({
    url: `/system/roles/${roleId}`,
    params,
    showSuccessMessage: true
  })
}

/**
 * 删除角色
 */
export function deleteRole(roleId: number) {
  return request.del<{ message: string }>({
    url: `/system/roles/${roleId}`,
    showSuccessMessage: true
  })
}

/**
 * 获取角色权限
 */
export function fetchRolePermissions(roleId: number) {
  return request.get<RolePermissionsResponse>({
    url: `/system/roles/${roleId}/permissions`
  })
}

/**
 * 更新角色权限
 */
export function updateRolePermissions(roleId: number, permissionIds: number[]) {
  return request.put<RolePermissionsResponse>({
    url: `/system/roles/${roleId}/permissions`,
    params: { permission_ids: permissionIds },
    showSuccessMessage: true
  })
}